package com.lgywin.userserver.server;

import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import com.lgywin.userserver.entity.generate.NetCode;
import com.lgywin.userserver.protobuf.MsgProto;
import com.lgywin.userserver.protobuf.NetProto;
import com.lgywin.userserver.service.UserService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class NetProHandleToService {

    @Resource
    private UserService userService;

    public void run(ChannelHandlerContext ctx, NetProto netProto) throws InvalidProtocolBufferException {
        int protoCode = netProto.getProtoCode();
        switch (protoCode) {
            case NetCode.HEARTBEATPROTO: {
                ctx.writeAndFlush(netProto);
            }
            break;

            case NetCode.MSGPROTO: {
                MsgProto bean = netProto.getCls(0).unpack(MsgProto.class);
                log.info("消息:" + bean.getCode());

                MsgProto.Builder retBean = MsgProto.newBuilder();
                retBean.setCode(99999);

                NetProto netProto2 = netProto.toBuilder().setProtoCode(NetCode.MSGPROTO).setCls(0, Any.pack(retBean.build())).build();
                ctx.writeAndFlush(netProto2);
            }
            break;
            //登录
            case NetCode.LOGINPROTO: {
                ctx.writeAndFlush(userService.login(ctx, netProto));
            }
            break;
            //注册
            case NetCode.REGPROTO: {
                ctx.writeAndFlush(userService.reg(ctx, netProto));
            }
            break;

            default:
                log.error("未知协议号 protoCode is error! protoCode=>" + protoCode);
                throw new RuntimeException("未知协议号 protoCode is error! protoCode=>" + protoCode);
        }
    }
}
